import axios from 'axios'
import router from '../router/index'
// axios.defaults.baseURL = "/api";
// axios.defaults.headers['Content-Type'] = 'application/json';
let http = axios.create({
    timeout:10000,
    baseURL:'/api',
    headers:{
        'Content-Type':'application/json'
    }
});
//配置生产和开发时的地址
//process.env.NODE_ENV==='development'?'xxx.xx.xx.xx:xxx':'xxx.xxx.xxx:xx'
//
// process.env.NODE_ENV==='development'?
//     http.defaults.baseURL = process.env.VUE_APP_BASE_URL:
//     http.defaults.baseURL = process.env.VUE_APP_BASE_URL
//请求前  请求前的拦截
//拦截的目的加token
http.interceptors.request.use(req=>{
    console.log('请求前');
    let token = localStorage.getItem('token');

    token && (req.headers['token'] = `Bearer ${token}`);
    return req
},error=>Promise.reject(error))
//响应后干什么
http.interceptors.response.use(resp=>{
    //后台给我们token 存起来
    resp.data.token && localStorage.setItem('token',resp.data.token)
    return resp
},error=>{
    let _resp = error.response
    switch (_resp.status) {
        case 401 :
            //把本地的token清除  跳转到login
            localStorage.removeItem('token')
            localStorage.removeItem('userName')
            localStorage.removeItem('type')
            alert('身份已过期,请重新登录')
            return router.push('/login')
    }
    return Promise.reject(error.response.data)
});

export default http